<template>
  <div>
    <div>
      <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="100" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <AjaxButton v-if="type !== 'show'" type="primary" :click="saveDialog">{{ btnText }}</AjaxButton>
    </div>

    <BaseDialog :visible.sync="showSupplierSelecter" title="供应商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <provideSearchHelper @close="showSupplierSelecter = false" @onConfirm="handleDealerSelectConfirm" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { isAuthorized, notifyAction } from '@/utils/index';
import provideSearchHelper from '@/pages/part/partPurchase/purchaseOrder/provideSearchHelper';
// import { addBrand, updateBrand } from '@/api/common/cars/brandcarsModels';
import { modifyPartCostPrice, modifyPartPlanPrice } from '@/api/part/inventoryManager/partCostAdjust';

export default {
  name: 'editPage',
  components: {
    provideSearchHelper
  },
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.conf = { add: '保 存', edit: '保 存' };
    this.saveData = null;
    return {
      formList: this.createFormList(),
      showSupplierSelecter: false, // 是否显示供应商选择
      customerCode: '',
      selectedCustomer: {
        // 选中的供应商信息customerCode
        customerName: '一汽大众汽车有限公司',
        customerCode: 'FAW-VW'
      }
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if (this.type === 'edit') {
        // debugger;
        // 更新接口需要的记录 ID
        // console.log(this.rowData.COST_AMOUNT);

        this.partNo = this.rowData.PART_NO;
        this.storageCode = this.rowData.STORAGE_CODE;
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '仓库代码',
          fieldName: 'STORAGE_CODE',
          disabled: true
          // rules: [{ required: true,message: '请输入仓库代码', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          disabled: true
          // rules: [{ required: true,message: '请输入配件代码',  trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          disabled: true
          // rules: [{ required: true,message: '请输入配件名称', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '原成本单价',
          fieldName: 'COST_PRICE',
          min: 0,
          disabled: true,
          onInput: props => {
            console.log(props, kkkks);
          }
          // rules: [{ required: true, message: '请输入原成本单价', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '数量',
          fieldName: 'STOCK_QUANTITY',
          disabled: true
          // rules: [{ required: true, message: '请输入数量', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'vSupplyId',
          placeholder: '请选择...',
          initialValue: '一汽大众汽车有限公司',
          noResetable: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.showProvideSearchHelper}></el-button>;
          },
          readonly: true,

          rules: [{ required: true, message: '请输入供应商', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '原成本金额',
          fieldName: 'COST_AMOUNT',
          disabled: true,
          initialValue: this.rowData.COST_AMOUNT,
          min: 0
          // rules: [{ required: true, message: '请输入原成本金额', trigger: 'blur' }]
        },

        {
          type: 'INPUT_NUMBER',
          label: '新成本单价',
          fieldName: 'NEW_PRICE',
          precision: 4,
          readonly: true,
          disabled: true,
          change: val => {
            this.calMoney(val);
          }
        },

        {
          type: 'INPUT',
          label: '新成本金额',
          fieldName: 'NEW_AMOUNT',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '调整金额',
          fieldName: 'ADJUST_AMOUNT',
          initialValue: '',
          change: val => {
            if (val) {
              let num = val / 1.13;
              let adjust = num.toFixed(2);
              this.formList.find(x => x.fieldName == 'ADJUST_COST').initialValue = adjust;
              let costAmount = this.formList.find(x => x.fieldName == 'COST_AMOUNT').initialValue;
              this.formList.find(x => x.fieldName == 'NEW_AMOUNT').initialValue = (Number(adjust) + Number(costAmount)).toFixed(2);
              let stockQuantity = this.formList.find(x => x.fieldName == 'STOCK_QUANTITY').initialValue;
              this.formList.find(x => x.fieldName == 'NEW_PRICE').initialValue = ((Number(adjust) + Number(costAmount)) / stockQuantity).toFixed(4);
              this.formList.find(x => x.fieldName == 'TAX_AMOUNT').initialValue = (val - num).toFixed(2);
            }
          },
          rules: [{ required: true, message: '请输入调整金额', trigger: 'blur' }]
        },

        {
          type: 'INPUT',
          label: '调整成本',
          fieldName: 'ADJUST_COST',
          initialValue: '',
          change: val => {
            console.log(val, '调增成本');
            if (val) {
              this.formList.find(x => x.fieldName == 'NEW_AMOUNT').initialValue = Number(this.rowData.COST_AMOUNT ? this.rowData.COST_AMOUNT : 0) + Number(val);
              // 调整金额  =  调整成本 + 税额
              let taxAmount = this.formList.find(x => x.fieldName == 'TAX_AMOUNT').initialValue;
              this.formList.find(x => x.fieldName == 'ADJUST_AMOUNT').initialValue = Number(taxAmount) + Number(val);
              let stockQuantity = this.formList.find(x => x.fieldName == 'STOCK_QUANTITY').initialValue;
              this.formList.find(x => x.fieldName == 'NEW_PRICE').initialValue = ((Number(this.rowData.COST_AMOUNT ? this.rowData.COST_AMOUNT : 0) + Number(val)) / stockQuantity).toFixed(4);
            }
          },
          rules: [{ required: true, message: '请输入调整成本', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '税额',
          fieldName: 'TAX_AMOUNT',
          initialValue: '',
          change: val => {
            if (val) {
              // 调整金额  =  调整成本 + 税额
              let adjustCost = this.formList.find(x => x.fieldName == 'ADJUST_COST').initialValue;
              this.formList.find(x => x.fieldName == 'ADJUST_AMOUNT').initialValue = Number(adjustCost) + Number(val);
            }
          },
          rules: [{ required: true, message: '请输入税额', trigger: 'blur' }]
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData !== null) {
        let res = {};
        if (this.type === 'add') {
          res = await addBrand(this.saveData);
        }
        if (this.type === 'edit') {
          // console.log(this.saveData, '-----saveData-----');
          // if (isAuthorized('1313', '13131003')) {
          this.saveData.STORAGE_NAME = this.rowData.STORAGE_NAME;
          console.log(this.saveData, '111111111111111111111');
          this.saveData.vSupplyId = this.customerCode;
          console.log(this.saveData, '22222222222222222222');
          res = await modifyPartPlanPrice(this.saveData, this.partNo, this.storageCode);
          // console.log(res);
          if (res.resultCode === 200) {
            notifyAction('采购价修改成功', 'success');
            this.closeDialog('refresh');
          }
        }
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },

    // 供应商选择点击确定
    handleDealerSelectConfirm(e) {
      this.selectedCustomer = e;
      console.log(e, 'e');
      this.formList.find(item => item.fieldName == 'vSupplyId').initialValue = e.customerName;
      this.customerCode = e.customerCode;
    },
    // 切换供应商选择展示
    showProvideSearchHelper() {
      this.showSupplierSelecter = true;
    },

    calMoney(val) {
      let num = this.formList[4].initialValue;
      this.formList[7].initialValue = val * num;
      this.formList = [...this.formList];
    }
  }
};
</script>

<style lang="less" scoped></style>
